package com.seata.account.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.seata.account.dao.mapper.AccountMapper;
import com.seata.account.dao.entity.Account;
import com.seata.account.service.AccountService;

import com.seata.core.exception.BusinessException;
import com.seata.core.support.LogSupport;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Objects;

/**
 * @author deeprado
 */
@Service("accountServiceImpl")
public class AccountServiceImpl extends ServiceImpl<AccountMapper, Account> implements AccountService {

    @Override
    public boolean decrease(Long userId, BigDecimal payAmount) throws BusinessException, InterruptedException {
        // 查询账户是否存在
        QueryWrapper<Account> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Account::getUserId, userId);
        Account account = this.getOne(queryWrapper);
        if (Objects.isNull(account)) {
            throw new BusinessException("账户不存在");
        }
        LogSupport.logInfo("------->尝试扣减账户开始, userId:{}, payAmount:{}", userId, payAmount);
        getBaseMapper().decrease(userId, payAmount);

        if (payAmount.equals(new BigDecimal(40))) {
            Thread.sleep(3000L);
            throw new BusinessException("尝试扣减账户 异常");
        }
        LogSupport.logInfo("------->尝试扣减账户结束");
        return true;
    }

    @Override
    public boolean compensateDecrease(Long userId, BigDecimal payAmount) throws BusinessException {
        LogSupport.logInfo("------->尝试补偿扣减账户开始account, userId:{}, payAmount:{}", userId, payAmount);
        getBaseMapper().decrease(userId, payAmount.negate());
        LogSupport.logInfo("------->尝试补偿扣减账户结束account");

        return true;
    }

}
